//
//  AUAddressPickerContentView.swift
//  CreditLoans
//
//  Created by 谢强 on 2017/12/9.
//  Copyright © 2017年 com.ucfpay. All rights reserved.
//

import UIKit

import AwesomeUBaseModule

private let AUAddressPickerContentViewCellIdentifier = "AUAddressPickerContentViewCellIdentifier"

// MARK:- <协议>
protocol AUAddressPickerContentViewDelegate: class {
    
    /// 滚动
    func pageContentView(_ pageContentView: AUAddressPickerContentView,
                         progress: CGFloat,
                         sourceIndex: Int,
                         targetIdex: Int,
                         address: String)
    
    /// 更新标题
    func updateTitle(_ pageContentView: AUAddressPickerContentView,
                     sourceIndex: Int,
                     address: String)
}

// MARK:- <Class>
class AUAddressPickerContentView: UIView {
    
    // 数据
    lazy var dataArray: [AUAddressPickerModel] = {
        var dataArray = [AUAddressPickerModel]()
        
        let bundle = Bundle.init(for: type(of: self))
        guard let bundleDict = bundle.infoDictionary, let bundleName = bundleDict["CFBundleName"] else {
            return dataArray
        }
        guard let path = bundle.path(forResource: "Address", ofType: "plist") else {
            return dataArray
        }
        
        let tempArray = NSArray(contentsOfFile: path)
        guard let array = tempArray as? [[String: Any]] else {
            return dataArray
        }
//        if let jsonData = try? JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted) {
//            if let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) {
//                print(jsonString)
//            }
//        }
        
//        let jsonData = try! JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
//        let str = String(data: jsonData, encoding: String.Encoding.utf8)!
//        print(str)
        
        for itemDict in array {
            dataArray.append(AUAddressPickerModel(dict: itemDict))
        }
        return dataArray
    }()
    
    var address: String = ""
    
    internal var completionCallback: AUAddressPickerCallback?
    
    // MARK: -属性
    fileprivate(set) var childViewControllers: [AUAddressPickerInnerVC]
    fileprivate weak var parrentViewController: UIViewController?
    
    fileprivate var startX: CGFloat = 0
    fileprivate var isForbidScrollDelegate: Bool = false
    
    weak var delegate: AUAddressPickerContentViewDelegate?
    
    // MARK: -懒加载
    lazy var collectionView: UICollectionView = { [weak self] in
        
        // layout
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        // collectionView
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.scrollsToTop = false
        collectionView.isPagingEnabled = true
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: AUAddressPickerContentViewCellIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        return collectionView
        }()
    
    // MARK: -构造函数
    init(frame: CGRect,
         childViewControllers: [AUAddressPickerInnerVC]?,
         parrentViewController: UIViewController?,
         scrollEnable: Bool) {
        self.childViewControllers = [AUAddressPickerInnerVC()]
        self.parrentViewController = parrentViewController
        
        super.init(frame: frame)
        
        setupUI()
        
        collectionView.isScrollEnabled = scrollEnable
        
        print("所有的省: \(dataArray.count)")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- <设置UI>
extension AUAddressPickerContentView {
    
    fileprivate func setupUI() {
        
        for childViewController in childViewControllers {
            parrentViewController?.addChildViewController(childViewController)
        }
        
        addSubview(collectionView)
        collectionView.frame = bounds
        
    }
}


// MARK:- <UICollectionViewDataSource>
extension AUAddressPickerContentView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childViewControllers.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AUAddressPickerContentViewCellIdentifier, for: indexPath)
        
        for subView in cell.contentView.subviews {
            subView.removeFromSuperview()
        }
        
        var childViewController = childViewControllers[indexPath.item]
        childViewController.view.frame = cell.contentView.bounds
        childViewController.view.tag = indexPath.item
        if indexPath.item == 0 {
            childViewController.dataArray = dataArray
        }
        cell.contentView.addSubview(childViewController.view)
        
        // 回调
        childViewController.selectedCallback = { [weak self] (address, childs) in
            
            let rate = Int(self!.collectionView.contentOffset.x) % Int(au_kScreenScale)
            if rate != 0 {return}
            
            self?.address = address
            
            let nextIndexPath = IndexPath(item: indexPath.item + 1, section: indexPath.section)
            
            // 更新标题
            self?.delegate?.updateTitle(self!, sourceIndex: indexPath.item, address: address)
            
            // 选择结束
            guard let sub = childs else {
                self?.completionCallback?()
                return
            }
            if !(sub.count > 0) {
                self?.completionCallback?()
                return
            }
                
            self?.isForbidScrollDelegate = false
            
            // 更新地址
            if nextIndexPath.item >= self!.childViewControllers.count { // 向右滚动
                // 获取滚动的起始位置
                self?.startX = self!.collectionView.contentOffset.x
                
                let innerVC = AUAddressPickerInnerVC()
                innerVC.dataArray = sub
                self?.childViewControllers.append(innerVC)
                self?.collectionView.reloadData()
                
            } else {    // 重新选择
                self?.updateControllers(indexPath: indexPath, childs: sub)
            }
            
            // 滚动
            self?.collectionView.scrollToItem(at: nextIndexPath, at: .centeredHorizontally, animated: true)
            
        }
        
        return cell
    }
}

// MARK:- <UICollectionViewDelegate>
extension AUAddressPickerContentView: UICollectionViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        isForbidScrollDelegate = false
        
        // 获取滚动的起始位置
        startX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isForbidScrollDelegate { return }
        
        var progress: CGFloat
        var sourceIndex: Int
        var targetIndex: Int
        
        let currentOffsetX: CGFloat = scrollView.contentOffset.x
        let scrollViewWidth: CGFloat = scrollView.frame.size.width
        
        if currentOffsetX > startX { // 向左滑动
            // 1. progress
            progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
            
            // 2.sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewWidth)
            
            // 3.targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= childViewControllers.count - 1 {
                targetIndex = childViewControllers.count - 1
            }
            
            // 4.完全划过去
            if currentOffsetX - startX == scrollViewWidth {
                progress = 1
                targetIndex = sourceIndex
            }
            
            // 解决bug
            if progress == 0 {return}
            
        } else { // 向右滑动
            // 1.progress
            progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
            
            // 2.targetIndex
            targetIndex = Int(currentOffsetX / scrollViewWidth)
            
            // 3.targetIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childViewControllers.count - 1 {
                sourceIndex = childViewControllers.count - 1
            }
        }
        delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIdex: targetIndex, address: address)
    }
}

// MARK:- <公共接口>
extension AUAddressPickerContentView {
    
    func setPage(currentIndex: NSInteger, animated: Bool) {
        
        guard currentIndex >= 0 && currentIndex < childViewControllers.count else {
            return
        }
        
        isForbidScrollDelegate = true
        
        let point = CGPoint(x: au_kScreenWidth * CGFloat(currentIndex), y: 0)
        collectionView.setContentOffset(point, animated: animated)
    }
    
    func updateControllers(indexPath: IndexPath, childs: [AUAddressPickerModel]) {
        
        let nextIndexPath = IndexPath(item: indexPath.item, section: indexPath.section)
        
        // 添加
        if nextIndexPath.item >= childViewControllers.count {
            // 获取滚动的起始位置
            startX = collectionView.contentOffset.x
            
            childViewControllers.append(AUAddressPickerInnerVC())
            
        } else {
            let sourceIndex = indexPath.item
            
            if sourceIndex < childViewControllers.count - 1 {
                print("更新Cell")
                
                let count = childViewControllers.count - 1 - sourceIndex
                
                if count > 0 {
                    // 要截掉的位置
                    let tempRange = NSMakeRange(sourceIndex + 1, count)
                    let range = Range(tempRange)
                    
                    for i in (sourceIndex + 1)..<(childViewControllers.count) {
                        childViewControllers[i].view.removeFromSuperview()
                        childViewControllers[i].removeFromParentViewController()
                    }
                    
                    childViewControllers.removeSubrange(range!)
                }
                
                let innerVC = AUAddressPickerInnerVC()
                for child in childs {
                    child.selected = false
                }
                innerVC.dataArray = childs
                childViewControllers.append(innerVC)
            }
        }
        
        collectionView.reloadData()
    }
}
